﻿using Consul;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JX.Infrastructure.Consul
{
    /// <summary>
    /// Consul服务提供者
    /// </summary>
    public class ConsulServiceProvider : IConsulServiceProvider
    {
        private readonly ConsulClient _consuleClient;

        /// <summary>
        /// 构造器注入
        /// </summary>
        /// <param name="uri">Consul的地址</param>
        public ConsulServiceProvider(Uri uri)
        {
            _consuleClient = new ConsulClient(consulConfig =>
            {
                consulConfig.Address = uri;
            });
        }

        /// <summary>
        /// 根据服务名称，得到服务地址列表
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="tag"></param>
        /// <param name="passingOnly"></param>
        /// <returns></returns>
        public async Task<IList<string>> GetServicesAsync(string serviceName, string tag = "", bool passingOnly = true)
        {
            // Health 当前consul里已注册的服务，健康检查的信息也拿过来
            // HTTP API 8500端口
            var queryResult = await _consuleClient.Health.Service(serviceName, tag, passingOnly);
            var result = new List<string>();
            foreach (var service in queryResult.Response)
            {
                result.Add(service.Service.Address + ":" + service.Service.Port);
            }
            return result;
        }
    }
}
